package com.example.utils;

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileWriter;
import java.util.Map;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

public class JsonToYamlConverter {

    // 将JSON文件转换为YAML文件
    public static void convertJsonToYaml(String jsonFilePath, String yamlFilePath) throws IOException {
        // 1. 读取JSON文件并解析为Map对象
        ObjectMapper objectMapper = new ObjectMapper();
        FileInputStream jsonFile = new FileInputStream(new File(jsonFilePath));

        Map<String, Object> jsonMap = objectMapper.readValue(jsonFile, Map.class);
        // 2. 设置YAML的格式选项
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // 使用块格式
        options.setPrettyFlow(true); // 美化输出

        // 3. 使用SnakeYAML将Map对象转换为YAML格式
        Yaml yaml = new Yaml(options);
        String yamlContent = yaml.dump(jsonMap);
        // 4. 将YAML内容写入YAML文件
        FileWriter yamlFile = new FileWriter(new File(yamlFilePath));
        yamlFile.write(yamlContent);
        yamlFile.close();

        System.out.println("JSON文件已成功转换为YAML文件！");
    }
}